package com.fz.crowdfunding.listener;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.fz.crowdfunding.bean.Permission;
import com.fz.crowdfunding.manager.service.PermissionService;
import com.fz.crowdfunding.util.Const;

public class StartSystemListener implements ServletContextListener
{
	
	public void contextDestroyed(ServletContextEvent arg0) {
		
	}
	//在服务器启动时，创建application对象时需要执行的方法
	public void contextInitialized(ServletContextEvent sce) {
		//1.将项目上下文路径(request.getContextPath())放置到application域中
		ServletContext application = sce.getServletContext();
		String contextPath = application.getContextPath();
		application.setAttribute("APP_PATH", contextPath);
		System.out.println("项目上下文路径APP_PATH...");
		
		System.out.println("将IOC容器对象存放到application域里");
		//获取ioc容器,利用ioc容器获得容器中的permissionService
		ApplicationContext ioc = WebApplicationContextUtils.getWebApplicationContext(application);
		PermissionService permissionService = ioc.getBean(PermissionService.class);
		
		//获取所有许可路径
		List<Permission> queryAllPermission = permissionService.queryAllPermission();
		Set<String> allURIs = new HashSet<String>();
		for (Permission permission : queryAllPermission) {
			allURIs.add("/"+permission.getUrl());
		}
		//服务器启动时调用该监听器，将所有许可路径放入application域中，方便以后直接获取许可路径
		application.setAttribute(Const.ALL_PERMISSION_URI, allURIs);
	}

}
